<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="货品编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主名称" prop="ownerName">
        <el-input
          v-model="queryParams.ownerName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['basics:WmsGoods:add']"
          >新增货品</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="WmsGoodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column
        label="货品类型名称"
        align="center"
        prop="goodsTypeName"
      />
      <el-table-column label="货品编号" align="center" prop="code" />
      <el-table-column label="货品条码" align="center" prop="barCode" />
      <el-table-column label="货品名称" align="center" prop="name" />
      <el-table-column label="货主名称" align="center" prop="ownerName" />
      <el-table-column label="质检方式" align="center" prop="inspectionType">
        <template #default="scope">
          <dict-tag
            :options="inspection_type"
            :value="scope.row.inspectionType"
          />
        </template>
      </el-table-column>
      <el-table-column label="温度要求" align="center" prop="temperatureType">
        <template #default="scope">
          <dict-tag
            :options="temperature_type"
            :value="scope.row.temperatureType"
          />
        </template>
      </el-table-column>
      <el-table-column label="承重要求" align="center" prop="bearingType">
        <template #default="scope">
          <dict-tag :options="bearing_type" :value="scope.row.bearingType" />
        </template>
      </el-table-column>
      <el-table-column label="指定库区" align="center" prop="areaName" />
      <el-table-column label="体积m³" align="center" prop="volume">
        <template #default="scope">
          <!-- 使用 toFixed(2) 保留两位小数 -->
          <span>{{
            scope.row.volume ? scope.row.volume.toFixed(2) : "--"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价(元)" align="center" prop="price" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column
        label="保质天数(天)"
        align="center"
        prop="guaranteeDay"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basics:WmsGoods:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basics:WmsGoods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="WmsGoodsRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="货品编码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="系统自动生成"
            :disabled="true"
            style="color: #666; background-color: #f5f7fa"
          />
        </el-form-item>
        <el-form-item label="货品类型" prop="goodsTypeId">
          <el-input
            v-model="form.goodsTypeId"
            placeholder="请输入货品类型名称或编码"
            :disabled="!open"
            class="type-input"
          />
        </el-form-item>
        <el-form-item label="货品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="货品条码" prop="barCode">
          <el-input v-model="form.barCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="货主" prop="ownerId">
          <el-input v-model="form.ownerId" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="质检方式" prop="inspectionType">
          <el-select v-model="form.inspectionType" placeholder="请选择">
            <el-option
              v-for="dict in inspection_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="温度要求" prop="temperatureType">
          <el-select v-model="form.temperatureType" placeholder="请选择">
            <el-option
              v-for="dict in temperature_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="承重要求" prop="bearingType">
          <el-select v-model="form.bearingType" placeholder="请选择">
            <el-option
              v-for="dict in bearing_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体积" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="指定库区" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择">
            <el-option
              v-for="area in areaList"
              :key="area.id"
              :label="area.name"
              :value="area.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="保质天数" prop="guaranteeDay">
          <el-input v-model="form.guaranteeDay" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">返回</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WmsGoods">
import { ref, reactive, watch, onMounted } from "vue";
import {
  listWmsGoods,
  getWmsGoods,
  delWmsGoods,
  addWmsGoods,
  updateWmsGoods,
  getMaxCode,
} from "@/api/basics/WmsGoods";
import { listWmsAreaQuery } from "@/api/basics/WmsAreaQuery";

const { proxy } = getCurrentInstance();
const { inspection_type, temperature_type, bearing_type } = proxy.useDict(
  "inspection_type",
  "temperature_type",
  "bearing_type"
);

const WmsGoodsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const formData = reactive({
  form: {
    // goodsTypeName: "",
    goodsTypeId: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    ownerId: null,
  },
  rules: {
    goodsTypeId: [
      {
        required: true,
        message: "请输入货品类型名称/货品类型编码",
        trigger: "blur",
      },
    ],
    areaId: [{ required: true, message: "指定库区不能为空", trigger: "blur" }],
    code: [{ required: true, message: "货品编号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "请输入货品名称", trigger: "blur" }],
    barCode: [{ required: true, message: "请输入货品条码", trigger: "blur" }],
    ownerId: [
      { required: true, message: "请输入货主名称/编码", trigger: "blur" },
    ],
    inspectionType: [
      {
        required: true,
        message: "质检方式",
        trigger: "change",
      },
    ],
    temperatureType: [
      {
        required: true,
        message: "温度要求",
        trigger: "change",
      },
    ],
    bearingType: [
      {
        required: true,
        message: "承重要求",
        trigger: "change",
      },
    ],
    volume: [{ required: true, message: "请输入数字", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(formData);
const areaList = ref([]);

// 获取库区列表
function getAreaList() {
  listWmsAreaQuery(queryParams.value).then((response) => {
    areaList.value = response.rows;
  });
}

onMounted(() => {
  // 在组件挂载时获取库区列表
  getAreaList();
});

/** 查询货品管理列表 */
function getList() {
  loading.value = true;
  listWmsGoods(queryParams.value).then((response) => {
    WmsGoodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    // goodsTypeName: null,
    goodsTypeId: null,
    code: null,
    name: null,
    barCode: null,
    ownerId: null,
    ownerName: null,
    inspectionType: null,
    temperatureType: null,
    bearingType: null,
    volume: null,
    warehouseId: null,
    areaId: null,
    areaName: null,
    price: null,
    unit: null,
    guaranteeDay: null,
    id: null,
    status: null,
    remark: null,
    createUser: null,
    createName: null,
    createTime: null,
    updateUser: null,
    updateName: null,
    updateTime: null,
    logicDel: null,
  };
  proxy.resetForm("WmsGoodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 调用后端接口获取最大编号
  getMaxCode().then((response) => {
    let nextNum = 1;
    if (response.data && response.data.startsWith("HP")) {
      nextNum = parseInt(response.data.replace(/\D/g, "")) + 1;
    }
    form.value.code = "HP" + String(nextNum).padStart(6, "0");
    open.value = true;
    title.value = "添加货品管理";
  });
};

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getWmsGoods(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改货品管理";
  });
}

/** 提交按钮 */
const submitForm = () => {
  if (!form.value.goodsTypeId) {
    proxy.$modal.msgError("请选择或输入有效的货品类型");
    return;
  }

  proxy.$refs["WmsGoodsRef"].validate((valid) => {
    if (!valid) return;

    const formDataToSubmit = {
      ...form.value,
      goodsTypeId: form.value.goodsTypeId, // 确保传递货品类型ID
    };

    if (formDataToSubmit.id) {
      // 更新货品信息
      updateWmsGoods(formDataToSubmit)
        .then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList(); // 刷新列表
        })
        .catch((err) => {
          proxy.$modal.msgError(err.message || "修改失败");
        });
    } else {
      // 新增货品信息
      addWmsGoods(formDataToSubmit)
        .then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList(); // 刷新列表
        })
        .catch((err) => {
          proxy.$modal.msgError(err.message || "新增失败");
        });
    }
  });
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除货品管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delWmsGoods(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
